<!--

/*
* Copyright (C) 2005-2013 University of Sydney
*
* Licensed under the GNU License, Version 3.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.gnu.org/licenses/gpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/


/**
* Applet for viewing data using transforms
*
* @author      Stephen White   <stephen.white@sydney.edu.au>
* @copyright   (C) 2005-2013 University of Sydney
* @link        http://Sydney.edu.au/Heurist
* @version     3.1.0
* @license     http://www.gnu.org/licenses/gpl-3.0.txt GNU License 3.0
* @package     Heurist academic knowledge management system
* @subpackage  Viewer/Transforms
*/

-->

<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <link rel="stylesheet" href="../../common/css/printview.css"/>
    <link rel="stylesheet" href="../../common/css/printview_print.css" media="print"/>
    <script src="../js/annotationHighlight.js"></script>
    <script src="../js/getAnnotationPointers.js"></script>
    <script type="text/javascript" src="../../external/jquery/jquery.js"></script>
    <script type="text/javascript" src="../../external/yui/2.8.2r1/build/yahoo-dom-event/yahoo-dom-event.js"></script>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&amp;sensor=false&amp;libraries=weather" ></script>
    <script src="http://api.simile-widgets.org/timeline/2.3.1/timeline-api.js?bundle=true" type="text/javascript"></script>
    <script src="loadPrintFormats.php"></script>
    <script>
      if (!jQuery && typeof $ == "function"){// ensure backwards compatability for publish sites with older jQuery code
        var jQuery = $;
      }
      function loadXMLDocFromFile(filename)
      {
        var xmlDoc=null;
        var errorMsg = "Error loading " + filename + " using XMLHttpRequest";
        var d;
        try {
          d = new XMLHttpRequest();
        } catch (trymicrosoft) {
          try {
            d = new ActiveXObject("Msxml2.XMLHTTP");
          } catch (othermicrosoft) {
            try {
              d = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (failed) {
              d = false;
            }
          }
        }
        if (d) {
          try{
            d.open("GET", filename, false);
            d.send("");
            xmlDoc=d.responseXML;
          }catch(e){
            alert(errorMsg + " Hint : " + e);
          }
        }else{
          alert("Your browser doesn't process XSL. Unable to view content.");
        }
        return xmlDoc;
      }

      function fillStyles(s) {
        var styleSelectElt = document.getElementById("transform_select");
        styleSelectElt.options[0] = new Option("Select a style...", "");
        styleSelectElt.options[0].disabled = true;
        var localStyleName;
        for (localStyleName in styles){
          styleSelectElt.appendChild( new Option(localStyleName,localStyleName));
          if (localStyleName == s) {
            styleSelectElt.selectedIndex = styleSelectElt.options.length -1;
          }
        }
        for (var grpIndex in top.HEURIST.transforms.groupOrder) {
          var grpName = top.HEURIST.transforms.groupOrder[grpIndex];
          var firstInGroup = true;
          for (var index in top.HEURIST.transforms.groups[grpName]){
            var transformID = top.HEURIST.transforms.groups[grpName][index];
            var transform = top.HEURIST.transforms.byID[transformID];
            if (transform["type"] && transform["type"].search(/XSLT/) !== -1) {
              if (firstInGroup){
                //create opt group
                var grp = document.createElement("optgroup");
                grp.label = grpName;
                styleSelectElt.appendChild(grp);
                firstInGroup = false;
              }
              styleSelectElt.appendChild( new Option(transform["label"],transformID));
              if (transform["label"] == s) {
                styleSelectElt.selectedIndex = styleSelectElt.options.length -1;
              }
            }
          }
        }
        styleSelectElt.appendChild(new Option("Generic XML", "0"));
      }

      var xml;
      var pageXMLs = {};
      var aReq;
      var selectedIds;
      var xsls = {};
      var query;
      var aquery;
      var loadingPage;
      var initted = false;
      var loadCount;	// to restict the number of pages that are loaded. Some queries gives all records.
      var maxLoadPages = 10;
      var curStyle = top.HEURIST.util.getDisplayPreference("defaultPrintView"); //saved default stylesheet
      if (!top.HEURIST.transforms.nameLookup[curStyle]){
        curStyle = "Default view";
      }
      var curQueryURL;
      var currentPage = 1;
      var totalRecordCount = 0;
      var resultsPerPage = 50;
      var pageCount = 0;
      var hBase = window.location.protocol + "//" + window.location.host +
      (top && top.HEURIST && top.HEURIST.basePath? top.HEURIST.basePath : window.location.pathname.match(/^\/[^\/]+\//));
      var database = (top && top.HEURIST && top.HEURIST.database? top.HEURIST.database.name :
        (location.search.match(/db=([^&]+)/) ? location.search.match(/db=([^&]+)/)[1]: ""));

      function init() {
        //initialize parameters
        if (top.HEURIST && top.HEURIST.search) {
          // style
          if (location.search.match(/style=([^&=#]*)/)) {
            var temp = location.search.match(/style=([^&=#]*)/)[1];
            //check if there is a template for this style
            if (top.HEURIST.transforms.nameLookup[temp] || styles[temp] || temp == "Default view") {
              curStyle = temp;
              top.HEURIST.util.setDisplayPreference("defaultPrintView",temp);
            }
          }
          //selection
          if (location.search.match(/selectedIds=([0-9,]*)/)){
            selectedIds = location.search.match(/selectedIds=([0-9,]*)/);
            if (selectedIds) {
              selectedIds = selectedIds.split(",");
            }
          }else if (top.HEURIST.search.getSelectedRecIDs().get().length > 0) {
            selectedIds = top.HEURIST.search.getSelectedRecIDs().get();
          }
          //query
          query = location.search.replace(/&?selectedIds=([0-9,]*)/,"");//strip off selected
          query = query.replace(/&?style=[^&=#]*/,"");//strip off style
          query = query.replace(/\?&/,"?");//if only a ? then remove it
          var q = query.match(/q=([^&=#]*)/);
          if (!q && top.HEURIST.parameters['q']){ //no query passed in so build one from HEURIST.params
            query = "?";
            for ( var paramName in top.HEURIST.parameters) {
              if (query.length ==1) {
                query += paramName + "=" + top.HEURIST.parameters[paramName];
              }else{
                query += "&" + paramName + "=" + top.HEURIST.parameters[paramName];
              }
            }
            //set paging parameters to match
            if (top.HEURIST.search.results &&
                top.HEURIST.search.results.totalQueryResultRecordCount) {
                    totalRecordCount = top.HEURIST.search.results.totalQueryResultRecordCount;
                }
            if (top.HEURIST.search.resultsPerPage) resultsPerPage = top.HEURIST.search.resultsPerPage;
            pageCount = Math.ceil(totalRecordCount / resultsPerPage);
            if (top.HEURIST.search.currentPage) currentPage = top.HEURIST.search.currentPage;
            offset = (currentPage -1)*resultsPerPage;
            if (query.search("limit")> -1) {
              query = query.replace(/limit=[^#&=]*/,"limit=" + resultsPerPage);
            }else{
              query += "&limit=" + resultsPerPage;
            }
            if (query.search("offset")>-1) {
              query = query.replace(/offset=[^#&=]*/,"offset=" + offset);
            }else{
              query += "&offset=" + offset;
            }
          }

          if (query && query.search("db")== -1){//add teh db name if it's not there
            query += "&db=" + database;
          }
          //					if (query && query.search("a=")== -1){
          //						query += "&a=1";
          //					}
          if (query && query.search("f=")== -1){//make sure we get a fresh read of the data
            query += "&f=1";
          }
          if (query && query.search("stub=")== -1){//add stubs
            query += "&stub=1";
          }
          if (query && query.search("woot=")== -1){//add woot
            query += "&woot=1";
          }
        }
        //load xml
        fillStyles(curStyle);

        //set event handlers
        if (top.HEURIST) {
          top.HEURIST.registerEvent(this,"heurist-selectionchange",onSelectionChange);
          top.HEURIST.registerEvent(this,"heurist-selectall",onSelectAll);
          top.HEURIST.registerEvent(this,"heurist-pagechange",onPageChange);
          //					top.HEURIST.registerEvent(this,"heurist-changestate",onChangeState);
        }
        //				top.HEURIST.search.appRegisterInterface("transform", this);

        if(!selectedIds || selectedIds.length == 0){
          clearAndDisplayMessage("No Records Selected from Search Results");
        }else{

        }
        initted =true;
        top.HEURIST.fireEvent(top,"heurist-transform-app-ready");
      }

      function getState(){
        return "style="+curStyle;
      }

      function setState(stateString){
        //				alert("setting state "+ stateString);
        if (typeof stateString == "string" && stateString.search(/=/) > -1){
          var stateVars = stateString.split(","),
          styleID,
          i,optIndex;
          for (i =0; i<stateVars.length; i++) {
            temp = stateVars[i].split("=");
            if (temp.length > 1 && typeof temp[0] == "string" && temp[0] == "style" && typeof temp[1] == "string" &&
              $("#transform_select > option[textContent="+temp[1]+"]").length > 0){
              curStyle = temp[1];
              $("#transform_select").children("option").each(function(i,obj){
                  if (obj.textContent == curStyle){
                    optIndex = i;
                  }
              });
              $("#transform_select").attr("selectedIndex",optIndex);
            }
          }
        }
        top.HEURIST.fireEvent(top,"heurist-transform-app-state-set");
      }


      var relatedRecListXSL;

      function displayRelatedRecords(recID,parentDiv){
        var showRelatedLink = parentDiv.firstChild;
        if (parentDiv.className.match(new RegExp('(\\s|^)loaded(\\s|$)'))) {
          if (parentDiv.className.match(new RegExp('(\\s|^)show(\\s|$)'))) {
            parentDiv.className = parentDiv.className.replace(" show", "");
            showRelatedLink.innerHTML = "Show related records";
            return;
          } else {
            parentDiv.className += " show";
            showRelatedLink.innerHTML = "Hide related records";
            return;
          };
        };

        if (parentDiv.className == "related-records show" ) {
          parentDiv.className = parentDiv.className.replace(" show", "");
          showRelatedLink.innerHTML = "Show related records";
          return;
        } else {
          showRelatedLink.className += " wait";
          showRelatedLink.innerHTML = "Loading related records";
          parentDiv.className += " show";

          var xmlRecDepth1 = loadXMLDocFromFile(top.HEURIST.baseURL+
            "export/xml/flathml.php?q=ids:"+recID+"&depth=1&woot=1"+
            (top.HEURIST.database.name? "&db=" + top.HEURIST.database.name:""));
          if (!xmlRecDepth1) {
            return;
          }
          if (!relatedRecListXSL) {
            relatedRecListXSL = loadXMLDocFromFile("xsl/relatedRecList.xsl");
          }
          var xhtmlResultDoc;
          if (window.ActiveXObject){
            var xmlResultStr = xmlRecDepth1.transformNode(relatedRecListXSL);
            xhtmlResultDoc=new ActiveXObject("Microsoft.XMLDOM");
            xhtmlResultDoc.async="false";
            xhtmlResultDoc.loadXML(xmlResultStr);
            // code for Mozilla, Firefox, Opera, etc.
          }else {
            var xsltProcessor=new XSLTProcessor();
            xsltProcessor.importStylesheet(relatedRecListXSL);
            xhtmlResultDoc = xsltProcessor.transformToFragment(xmlRecDepth1,document);
          }
          parentDiv.appendChild(xhtmlResultDoc);
          parentDiv.className += " loaded";

          showRelatedLink.className = parentDiv.firstChild.className.replace(" wait", "");
          showRelatedLink.innerHTML = "Hide related records";
        }
      }

      function objFromArr(arr)
      {
        var obj = {};
        for(var i=0;i<arr.length;i++)
        {
          obj[arr[i]]="";
        }
        return obj;
      }

      var newSelectionIds, newSelectionMap, alreadySelectedMap;

      function onPageChange(eventType, argList) {// saw TODO change this to update the selection for levels
        // if a level is not loaded then load synch
        if (parent.document.getElementById("p").className == "yui-hidden") {
          return false;
        }
        clearAndDisplayLoading();
        //if page xml not loaded then load sync
        if (eventType == "heurist-pagechange"){
          var page = 0;
          if (argList && argList.match("pageNum")) {
            var page = argList.match("pageNum=(\\d+)")
            page = page[1];
          }else if (top.HEURIST.search.currentPage > 0) {
            page = top.HEURIST.search.currentPage;
          }
          if (page > 0  && page != currentPage && page <= pageCount){
            currentPage = page;
            if (!pageXMLs[page]){ //load pageXML now
              var pageQuery = query;
              pageQuery = pageQuery.replace(/limit=[^#&=]*/,"limit=" + resultsPerPage).replace(/offset=[^#&=]*/,"offset=" + (page-1)*resultsPerPage);
              var url = top.HEURIST.baseURL+ "export/xml/flathml.php" + pageQuery;
              var errorMsg = "Error loading " + url + " using XMLHttpRequest";
              pageXMLs[page] = loadXMLDocFromFile(url);
            }
            xml = pageXMLs[page];
            selectedIds = [];
            displayResultPage(curStyle,page);
          }
        }
      }

      function onSelectAll(eventType, argList) {// TODO  change this to showAll
        function getNodeContents(elem, nodeName,index) {
          if(!elem) return elem;
          var nodes = elem.getElementsByTagName(nodeName);
          if (!isNaN(index)){
            return nodes[index];
          }
          return elem;
        }
        //if page xml not loaded then load sync
        if (parent.document.getElementById("p").className == "yui-hidden") {
          return false;
        }else if (eventType == "heurist-selectall"){//should be show all
          var tempXML,recordsNode;
          for (var page = 1; page <= pageCount; page++){
            if (!pageXMLs[page]){ //load pageXML now
              var pageQuery = query;
              pageQuery = pageQuery.replace(/limit=[^#&=]*/,"limit=" + resultsPerPage).replace(/offset=[^#&=]*/,"offset=" + (page-1)*resultsPerPage);
              var url = top.HEURIST.baseURL+ "export/xml/flathml.php" + pageQuery;
              var errorMsg = "Error loading " + url + " using XMLHttpRequest";
              pageXMLs[page] = loadXMLDocFromFile(url);
            }
            if (page == 1){
              tempXML = pageXMLs[page].cloneNode(true); //saw TODO  check if this clones or not
              if(!tempXML){
                tempXML = pageXMLs[page];
              }
              recordsNode = getNodeContents(tempXML,"records",0);
            }else{
              tempXML = pageXMLs[page].cloneNode(true); //saw TODO  check if this clones or not
              if(!tempXML){
                tempXML = pageXMLs[page];
              }
              var recordNodes = getNodeContents(tempXML,"records",0);
              if (!recordsNode) {
                recordsNode = recordNodes;
              }else{
                for (var i =1; i<recordNodes.childNodes.length; i++) {
                  recordsNode.appendChild(recordNodes.childNodes[i].cloneNode(true));
                }
              }
            }
          }
          pageXMLs[0] = recordsNode;
          selectedIds = [];
          displayResultPage(curStyle,0);
        }
      }

      var FlatHMLQuery = {'filter':"",'query':"",'maxDepth':0,'selectIDs':""};
      function onSelectionChange(eventType, argList) {
        if (parent.document.getElementById("p").className == "yui-hidden") { //if tab not current ignore event
          return false;
        }else if (eventType == "heurist-selectionchange"){	// saw TODO change this to update the selection for levels
          // if a level is not loaded then load synch
          var layoutString = top.HEURIST.search.getLayoutString();//calls back through getAppState
          var selFilter = top.HEURIST.search.getSelectedString();
          var rtFilter = top.HEURIST.search.getPushDownFilter("rectype");
          var rleFilter = top.HEURIST.search.getPushDownFilter("reltype");
          var ptrFilter = top.HEURIST.search.getPushDownFilter("ptrtype");
          var filter = "" + (rtFilter.length > 0 &&  rtFilter[1] != "" ? "&" + rtFilter[1] : "")
          + (rleFilter.length > 0 &&  rleFilter[1] != "" ? "&" + rleFilter[1] : "")
          + (ptrFilter.length > 0 &&  ptrFilter[1] != "" ? "&" + ptrFilter[1] : "");
          /*					newSelectionIds = [];
          if (top.HEURIST.search.getLevelSelectedRecIDs("0").get().length > 0) {
          newSelectionIds = top.HEURIST.search.getLevelSelectedRecIDs("0").get();
          }else if (argList && argList.match("selectedIds")) {
          var ids = argList.match("selectedIds=(\\d+(?:,\\d+)*)");
          if (ids && ids[1]) newSelectionIds = ids[1].split(",");
          }*/
          var maxDepth = Math.max(layoutString[0],0);
          var newSelectionIDs = top.HEURIST.search.getSelectedRecIDs();
          newSelectionIDs = newSelectionIDs.toArray().join();
          if (FlatHMLQuery.filter != filter || FlatHMLQuery.maxDepth < maxDepth ||FlatHMLQuery.query != top.HEURIST.parameters['q']) {
            var pageQuery = "?w=all&fc=1&woot=1&depth="+ maxDepth +
            "&q=" +(top.HEURIST.parameters['q']&& top.HEURIST.parameters['q'].length >0 ? top.HEURIST.parameters['q'] :"")+
            (filter.length > 0 ? filter : "") +
            (layoutString.length > 0 &&  layoutString[1] != "" ? "&" + layoutString[1] : "") +
            (selFilter.length > 0 &&  selFilter[1] != "" ? "&" + selFilter[1] : "") +
            ($("#expandColl").attr("checked") ? "&expandColl=1" : "") +
            (top.HEURIST.database.name? "&db=" + top.HEURIST.database.name:"");
            curQueryURL = top.HEURIST.baseURL+ "export/xml/flathml.php" + pageQuery;
            var errorMsg = "Error loading " + curQueryURL + " using XMLHttpRequest";
            clearAndDisplayLoading();
            xml = loadXMLDocFromFile(curQueryURL);
            FlatHMLQuery.filter = filter;
            if (FlatHMLQuery.maxDepth < maxDepth) {
              FlatHMLQuery.maxDepth = maxDepth;
            }
            FlatHMLQuery.query = top.HEURIST.parameters['q'];
          }else if(FlatHMLQuery.selectIDs != newSelectionIDs &&
                    xml.getElementsByTagName("hml") &&
                    xml.getElementsByTagName("hml").item(0).firstChild){
            //replace xml selids node with new ids.
            if (!xml.getElementsByTagName("selectedIDs").item(0)) {// no previous selected records so need to create node
              var si = xml.createElement("selectedIDs");
              var ds = xml.getElementsByTagName("dateStamp").item(0);
              var h = xml.getElementsByTagName("hml").item(0);
              si.appendChild(xml.createTextNode(newSelectionIDs));
              h.insertBefore(si,ds);
            }else{
              xml.getElementsByTagName("selectedIDs").item(0).firstChild.nodeValue = newSelectionIDs;
            }
            //update record nodes with selected attribute
            var selIds = newSelectionIDs.split(",");
            $("record[selected='yes']",$(xml)).attr("selected","no");
            $("record[selected='no']",$(xml)).each(function(i,rec){
                var recID = $(rec).children("id").text();
                if(selIds.indexOf(recID) > -1) $(rec).attr("selected","yes");
            });
            //change selids in curQueryURL
            curQueryURL = curQueryURL.replace(/selids=\{.*\}/,selFilter[1]);
          }
          FlatHMLQuery.selectIDs = newSelectionIDs;
          selectedIds = newSelectionIDs.split(",");
          displayResultDoc(curStyle,xml);
          /*
          var selDivs = $('div[class~=selected]');
          if (selDivs) selDivs.map(function(a){ return this.id;}).map(function(i){
          if (newSelectionMap[this]) {
          alreadySelectedMap[this] = "";
          }else{
          $('div#'+ this).removeClass("selected");
          }
          });
          $(newSelectionIds).map(function(i){
          if (!alreadySelectedMap[this]){
          $('div#'+ this).addClass("selected");
          }
          });
          if (selectedIds && selectedIds.length > 0 &&
          $('div#'+selectedIds[selectedIds.length-1],
          $('iframe[id=viewer-frame]',top.document).get(0).contentDocument).length > 0) {
          $('div#'+selectedIds[selectedIds.length-1],$('iframe[id=viewer-frame]',top.document).get(0).contentDocument).get(0).scrollIntoView();
          }
          */
        }
      }

      function updateSelection(){//Mark any record divs id in selected as class selected (visible)
        if(selectedIds && selectedIds.length>0) {
          for (var i = 0; i < selectedIds.length; i++) {
            $('div[class~=record]').filter('div[id='+ selectedIds[i] +']').addClass("selected");
          }
        }
      }

      function clearAndDisplayLoading(){
        var resultDiv =document.getElementById("displayResult");
        while (resultDiv.childNodes[0]) resultDiv.removeChild(resultDiv.childNodes[0]);
        var loadingDiv = document.createElement("div");
        loadingDiv.id = "loading";
        resultDiv.appendChild(loadingDiv);
      }

      function clearAndDisplayMessage(message){
        var resultDiv =document.getElementById("displayResult");
        while (resultDiv.childNodes[0]) resultDiv.removeChild(resultDiv.childNodes[0]);
        var noSelectedDiv = document.createElement("div");
        noSelectedDiv.id = "errorMsg";
        noSelectedDiv.innerHTML = "<div style='height:50%'></div><span>"+message+"</span>";
        resultDiv.appendChild(noSelectedDiv);
      }

      function changeTransform(transformID){
        if (transformID == 0) {
          curStyle = "Generic XML";
        }else if (top.HEURIST.transforms.byID[transformID]) {
          curStyle = top.HEURIST.transforms.byID[transformID].label;
        }else if (isNaN(transformID)){
          curStyle = transformID;
        }else{
          curStyle = "Default view";
        }
        top.HEURIST.util.setDisplayPreference("defaultPrintView",curStyle);
        displayResultDoc(curStyle,xml);
      }

      function displayResultDoc(style,xmlDoc){
        if (style == null || style == "") {
          clearAndDisplayMessage("Please select a transform template");
          return;
        }
        var resultDiv =document.getElementById("displayResult");
        var xhtmlResultDoc = "";
        function clearResult(resultDiv) {
          while (resultDiv.childNodes[0]) resultDiv.removeChild(resultDiv.childNodes[0]);
        }

        if (style == "Generic XML") {
          var ser = new XMLSerializer();
          var genXML = ser.serializeToString( xmlDoc.documentElement.cloneNode());
          xhtmlResultDoc = document.createTextNode(genXML);
        }else{
          if (!xsls[style]){
            if (top.HEURIST.transforms.nameLookup[style]){
              var transID = top.HEURIST.transforms.nameLookup[style];
              var uri = encodeURIComponent(top.HEURIST.transforms.byID[transID].uri);
              if (uri) {
                xsls[style]=loadXMLDocFromFile(top.HEURIST.baseURL + "viewers/printview/loadXSLTemplate.php?db="+database+"&style=" + uri);
              }
            }else{
              if (styles && styles[style] && styles[style][0]){
                xsls[style]=loadXMLDocFromFile(top.HEURIST.baseURL + "viewers/printview/loadXSLTemplate.php?db="
                                                    +database+"&style=" + styles[style][0]);
              }
            }
          }
          if (!xsls[style]) {
            alert("Unable to read '"+ style +"' file, check to see if this style sheet is readable in your browser or another browser.");
            return;
          }else if ( xsls[style].activeElement &&
                    (xsls[style].activeElement.nodeName == "parsererror" || xsls[style].activeElement.nodeName == "error")) {
                    //the transform is invalid, tell the user
            alert("The tranformation you have chosen is invalid. \n Please contact the owner/creator of the tranform");
            //and remove it from the list of choices
            var sElt = document.getElementById("transform_select");
            var optElt = sElt.options[sElt.selectedIndex];
            if (optElt.text == style){ // we have a match, not sure why we wouldn't
              if ((optElt.previousSibling.nodeName == "OPTGROUP") &&
                (optElt.nextSibling.nodeName == "OPTGROUP" || sElt.selectedIndex == sElt.length -1)){
                //last option in a group so remove previousSibling also
                var optGrpElt = optElt.previousSibling;
                sElt.removeChild(optGrpElt);
              }
              sElt.removeChild(optElt);
            }
            //and remove the document
            delete xsls[style];
            curStyle = null;
            sElt.selectedIndex = 0;
            clearAndDisplayMessage("Please select a transform template");
            return;
          }
          // code for IE
          if (window.ActiveXObject){// saw TODO change this transform a combined document for related results
            var xmlResultStr = xmlDoc.transformNode(xsls[style]);
            xhtmlResultDoc=new ActiveXObject("Microsoft.XMLDOM");
            xhtmlResultDoc.async="false";
            xhtmlResultDoc.loadXML(xmlResultStr);
            // code for Mozilla, Firefox, Opera, etc.
          }else {
            var xsltProcessor=new XSLTProcessor();// saw TODO change this transform a combined document for related results
            xsltProcessor.reset();
            try{
              xsltProcessor.importStylesheet(xsls[style]);
            }catch(e){
              alert("Unable to load the '"+ style + "' transform. \n"+
                "Please select a different transform. \n\n"+
                "The xsltProcessor returned Error Message:\n\t"+e.message);
              clearAndDisplayMessage(style+" transform loading problem, please select a different transform above");
              return;
            }finally{
              delete xsltProcessor;
            }
            if (xsltProcessor){
              try{
                xhtmlResultDoc = xsltProcessor.transformToFragment(xmlDoc,document);
              }catch(e){
                alert("The '"+ style + "' transform had an error during transformation. \n"+
                  "You might try different data or select a different transform. \n\n"+
                  "The xsltProcessor returned Error Message:\n\t"+e.message);
                clearAndDisplayMessage(style+" transformation error. Please select different data or a different transform above");
                return;
              }finally{
                delete xsltProcessor;
              }
            }
          }
        }
        clearResult(resultDiv);
        createTools(style);
        resultDiv.appendChild(xhtmlResultDoc);
        updateSelection();
      }

      function displayResultPage(style,page){
        var resultDiv =document.getElementById("displayResult");
        var xhtmlResultDoc = "";
        function clearResult(resultDiv) {
          while (resultDiv.childNodes[0]) resultDiv.removeChild(resultDiv.childNodes[0]);
        }

        if (style == "Generic XML") {
          xhtmlResultDoc = pageXMLs[page].documentElement;
        }else{
          if (!xsls[style]){
            xsls[style]=loadXMLDocFromFile(styles[style][2]);
          }
          if (!xsls[style]) {
            alert("Unable to read .xsl file, check to see if this style sheet is readable in your browser or another browser.");
            return;
          }
          // code for IE
          if (window.ActiveXObject){// saw TODO change this transform a combined document for related results
            var xmlResultStr = pageXMLs[page].transformNode(xsls[style]);
            xhtmlResultDoc=new ActiveXObject("Microsoft.XMLDOM");
            xhtmlResultDoc.async="false";
            xhtmlResultDoc.loadXML(xmlResultStr);
            // code for Mozilla, Firefox, Opera, etc.
          }else {
            var xsltProcessor=new XSLTProcessor();// saw TODO change this transform a combined document for related results
            xsltProcessor.importStylesheet(xsls[style]);
            xhtmlResultDoc = xsltProcessor.transformToFragment(pageXMLs[page],document);
          }
        }
        clearResult(resultDiv);
        resultDiv.appendChild(xhtmlResultDoc);
        updateSelection();
      }

      //scroll viewer back to top
      function backToTop(){
        var resultDiv =document.getElementById("displayResult");
        resultDiv.scrollTop = 0;
      }

      var annoSymbology = {}; //default is to add "comment" annotations  with lightBlue highlight

      function createTools(style){
        var buttonBar = $("#buttonBar");
        // remove all buttons
        buttonBar.html("");
        annoSymbology = {};
        //check if this style is a transform
        if (top.HEURIST.transforms.nameLookup[style]) {
          var transID = top.HEURIST.transforms.nameLookup[style];
          //check if there are tools for this transform
          if (top.HEURIST.tools.byTransform[transID]){
            var toolIDs = top.HEURIST.tools.byTransform[transID];
            //for each tool add button to bar and if annotation tool then add symbology
            for (var i in toolIDs) {
              var tool = top.HEURIST.tools.byId[toolIDs[i]];
              // if tool is for annotations then capture the symbology
              if (top.HEURIST.magicNumbers['RT_ANNOTATION'] &&
                tool.rt == top.HEURIST.rectypes.typedefs[top.HEURIST.magicNumbers['RT_ANNOTATION']].commonFields[top.HEURIST.rectypes.typedefs.commonNamesToIndex['rty_ConceptID']]){
                annoSymbology[tool.value] = tool.colour;
                //todo : set icon or superscript or subscript
              }
              var a = document.createElement("a");
              a.href = tool.command;
              var divTool = document.createElement("div");
              a.appendChild(divTool);
              divTool.className = "annotationLink"; //inherit standard stuff
              divTool.title = tool.name;
              if (tool.colour) {
                divTool.style.backgroundColor = tool.colour;
              }
              if (tool.img) {
                divTool.style.backgroundImage = "url('" + tool.img + "')";
              }
              buttonBar.append(a);
            }
          }
        }
        //set annoSymbology
        setAnnoSymbology(annoSymbology);
      }

      // read transform structure for buttons bar commands
      //
      function addAnnotation(annoType){
        if (!annoType) {
          annoType = 'Comment';
        }
        var contentDivs = $(".annotatedDocument div.content").get();
        if (!contentDivs[0]){
          alert("No content container element was found. Please use format that allows annotation. Try TeiView. ");
          return;
        }
        var annoStruct = window.findSelectionAddressInDocs(contentDivs);
        if (!annoStruct || !annoStruct.addr) {
          alert("No selection was found. Please make a selection and then press Annotation Button.");
          return;
        }
        var recTitle = $(annoStruct.docElem).attr("recTitle");
        var recID = $(annoStruct.docElem).attr("recID");
        /*
        confirm(" Would you like to add an annotation to '" +recTitle+ "' as follows:\n " +
        "Start  Elem:" + annoStruct.addr.startElems.join(":") +
        " Word:" + annoStruct.addr.startWord + "\n" +
        "End  Elem:" + annoStruct.addr.endElems.join(":") +
        " Word:" + annoStruct.addr.endWord)+ " ?"; */
        var title = "Add new record "+top.HEURIST.util.getRectypeIconAndName(top.HEURIST.magicNumbers['RT_ANNOTATION']);

        top.HEURIST.util.popupURL(window, top.HEURIST.basePath +'records/add/formAddRecordPopup.html?rectype='+
          top.HEURIST.magicNumbers['RT_ANNOTATION']+
          '&addr='+annoStruct.addr.startElems.join(",") +":"+
          annoStruct.addr.startWord +":"+
          annoStruct.addr.endElems.join(",") +":"+
          annoStruct.addr.endWord +
          (recID ? '&trgRecID='+recID : "") +	//TODO SAW : need to change this to conform to new annotation style
          (annoStruct.addr.text != ""  ? '&text='+ annoStruct.addr.text : "") +
          (recTitle ? '&trgRecTitle='+recTitle : "") +
          (annoType ? '&type='+annoType : "") +
          '&db='+ (window.HEURIST && window.HEURIST.parameters && window.HEURIST.parameters.db ? window.HEURIST.parameters.db :
            (top.HEURIST.parameters.db?top.HEURIST.parameters.db:
              (top.HEURIST.database.name? top.HEURIST.database.name:''))),
          {	title: title,
            callback: function(title, bd, bibID) {
              if (bibID) {
                //save scroll location
                //reload Document
                xml = loadXMLDocFromFile(curQueryURL);
                displayResultDoc(curStyle,xml);
                //setScroll location
              } else {
                alert("annotation didn't save please try again");
              }
            }
        });

      }
      function editAnnotation(annoID){
        if (!annoID) {
          return;
        }
        top.HEURIST.util.popupURL(window, top.HEURIST.basePath +'records/edit/formEditRecordPopup.html?recID='+annoID ,
          {	width: 800,
            height: 600,
            callback: function(title, bd) {
              if (bd) {
                //save scroll location
                //reload Document
                xml = loadXMLDocFromFile(curQueryURL);
                displayResultDoc(curStyle,xml);
                //setScroll location
              } else {
                alert("annotation didn't save please try again");
              }
            }
        });

      }
      //			$(document).ready(function(){initted =true;});
    </script>

  </head>
  <body onLoad="init()">

    <div class="banner">
      <select id="transform_select" style="width: 180px;" onChange="changeTransform(this.options[this.selectedIndex].value);">
      </select>
      <a href="javascript:window.print()"><div id="printingLink"></div></a>
      <div id="buttonBar">
      </div>
      <input type="checkbox" id="expandColl" />
      <label for="expandColl">Expand Collections</label>
      <a href="javascript:window.backToTop()" style="float: right;">to top</a>
    </div>
    <div id="displayResult" ></div>
  </body>
</html>
